<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>权限管理系统 - 基于ESSH数据库</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        h1, h2 {
            color: #333;
            border-bottom: 2px solid #007bff;
            padding-bottom: 10px;
        }
        input, select, button {
            padding: 8px 12px;
            margin: 5px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        button {
            background-color: #007bff;
            color: white;
            border: none;
            cursor: pointer;
        }
        button:hover {
            background-color: #0056b3;
        }
        .result {
            margin-top: 15px;
            padding: 15px;
            background-color: #f8f9fa;
            border-radius: 4px;
            border-left: 4px solid #007bff;
        }
        .user-card {
            border: 1px solid #dee2e6;
            border-radius: 4px;
            padding: 15px;
            margin: 10px 0;
            background-color: #f8f9fa;
        }
        .role-badge {
            display: inline-block;
            background: #17a2b8;
            color: white;
            padding: 3px 8px;
            border-radius: 12px;
            font-size: 12px;
            margin: 2px;
        }
        .menu-item {
            background: #28a745;
            color: white;
            padding: 3px 8px;
            border-radius: 4px;
            font-size: 12px;
            margin: 2px;
            display: inline-block;
        }
    </style>
</head>
<body>
<h1>🔐 权限管理系统 - 基于ESSH数据库</h1>

<!-- 任务一：查询特定用户及其角色 -->
<div class="container">
    <h2>📋 任务一：查询用户及其角色</h2>
    <p><strong>要求：</strong>根据登录名查询用户信息及其所有角色（一对多查询）</p>
    <div>
        <input type="text" id="loginname" placeholder="输入登录名（如：admin）">
        <button onclick="getUserRoles()">查询用户角色</button>
    </div>
    <div id="userResult" class="result"></div>
</div>

<!-- 任务二：查询角色及其权限 -->
<div class="container">
    <h2>🎯 任务二：查询角色及其权限</h2>
    <p><strong>要求：</strong>根据角色名称查询角色信息及其所有菜单权限（一对多查询）</p>
    <div>
        <input type="text" id="roleName" placeholder="输入角色名称（如：管理员角色）">
        <button onclick="getRoleMenus()">查询角色权限</button>
    </div>
    <div id="roleResult" class="result"></div>
</div>

<!-- 任务三：综合查询 -->
<div class="container">
    <h2>🔍 任务三：综合查询用户</h2>
    <p><strong>要求：</strong>根据条件搜索用户，并显示角色信息（动态SQL + 多对多查询）</p>
    <div>
        <input type="text" id="searchLoginname" placeholder="登录名（模糊匹配）">
        <input type="text" id="searchName" placeholder="真实姓名（模糊匹配）">
        <input type="text" id="searchEmail" placeholder="邮箱（模糊匹配）">
        <select id="searchStatus">
            <option value="">全部状态</option>
            <option value="0">正常</option>
            <option value="1">禁用</option>
        </select>
        <button onclick="searchUsers()">搜索用户</button>
        <button onclick="searchUsersWithPage()">分页搜索</button>
    </div>
    <div id="searchResult" class="result"></div>
</div>

<script>
    // 任务一：查询用户角色
    async function getUserRoles() {
        const loginname = document.getElementById('loginname').value;
        if (!loginname) {
            alert('请输入登录名');
            return;
        }

        try {
            const response = await fetch(`/api/users/${loginname}`);
            if (!response.ok) throw new Error('用户不存在');
            const user = await response.json();

            let html = `<div class="user-card">
                    <h3>👤 用户信息</h3>
                    <p><strong>登录名：</strong> ${user.loginname}</p>
                    <p><strong>真实姓名：</strong> ${user.name}</p>
                    <p><strong>邮箱：</strong> ${user.email || '无'}</p>
                    <p><strong>手机：</strong> ${user.mobilephone || '无'}</p>
                    <p><strong>状态：</strong> <span style="color: ${user.status === 0 ? 'green' : 'red'}">${user.status === 0 ? '✅ 正常' : '❌ 禁用'}</span></p>
                    <h4>🎭 角色列表：</h4>`;

            if (user.roles && user.roles.length > 0) {
                user.roles.forEach(role => {
                    html += `<span class="role-badge">${role.name}</span>`;
                });
            } else {
                html += `<p>该用户暂无角色</p>`;
            }
            html += `</div>`;

            document.getElementById('userResult').innerHTML = html;
        } catch (error) {
            document.getElementById('userResult').innerHTML = `<p style="color: red;">错误：${error.message}</p>`;
        }
    }

    // 任务二：查询角色权限
    async function getRoleMenus() {
        const roleName = document.getElementById('roleName').value;
        if (!roleName) {
            alert('请输入角色名称');
            return;
        }

        try {
            const response = await fetch(`/api/roles/name/${encodeURIComponent(roleName)}`);
            if (!response.ok) throw new Error('角色不存在');
            const role = await response.json();

            let html = `<div class="user-card">
                    <h3>🎭 角色信息</h3>
                    <p><strong>角色名称：</strong> ${role.name}</p>
                    <p><strong>描述：</strong> ${role.description || '无'}</p>
                    <h4>📁 菜单权限：</h4>`;

            if (role.menus && role.menus.length > 0) {
                html += `<div>`;
                role.menus.forEach(menu => {
                    html += `<span class="menu-item">${menu.name}</span>`;
                });
                html += `</div>`;
            } else {
                html += `<p>该角色暂无菜单权限</p>`;
            }
            html += `</div>`;

            document.getElementById('roleResult').innerHTML = html;
        } catch (error) {
            document.getElementById('roleResult').innerHTML = `<p style="color: red;">错误：${error.message}</p>`;
        }
    }

    // 任务三：综合查询
    async function searchUsers() {
        const loginname = document.getElementById('searchLoginname').value;
        const name = document.getElementById('searchName').value;
        const email = document.getElementById('searchEmail').value;
        const status = document.getElementById('searchStatus').value;

        let url = '/api/users/search?';
        const params = [];
        if (loginname) params.push(`loginname=${encodeURIComponent(loginname)}`);
        if (name) params.push(`name=${encodeURIComponent(name)}`);
        if (email) params.push(`email=${encodeURIComponent(email)}`);
        if (status) params.push(`status=${status}`);

        url += params.join('&');

        try {
            const response = await fetch(url);
            const users = await response.json();

            let html = '<h3>🔍 查询结果：</h3>';
            if (users.length === 0) {
                html += '<p>没有找到匹配的用户</p>';
            } else {
                users.forEach(user => {
                    html += `<div class="user-card">
                            <p><strong>👤 ${user.loginname}</strong> (${user.name})</p>
                            <p><strong>邮箱：</strong> ${user.email || '无'}</p>
                            <p><strong>手机：</strong> ${user.mobilephone || '无'}</p>
                            <p><strong>状态：</strong> <span style="color: ${user.status === 0 ? 'green' : 'red'}">${user.status === 0 ? '✅ 正常' : '❌ 禁用'}</span></p>
                            <p><strong>角色：</strong> `;

                    if (user.roles && user.roles.length > 0) {
                        user.roles.forEach(role => {
                            html += `<span class="role-badge">${role.name}</span>`;
                        });
                    } else {
                        html += '无角色';
                    }
                    html += `</p></div>`;
                });
            }

            document.getElementById('searchResult').innerHTML = html;
        } catch (error) {
            document.getElementById('searchResult').innerHTML = `<p style="color: red;">搜索错误：${error.message}</p>`;
        }
    }

    // 分页搜索
    async function searchUsersWithPage() {
        const loginname = document.getElementById('searchLoginname').value;
        const name = document.getElementById('searchName').value;
        const email = document.getElementById('searchEmail').value;
        const status = document.getElementById('searchStatus').value;

        let url = '/api/users/search/page?';
        const params = [];
        if (loginname) params.push(`loginname=${encodeURIComponent(loginname)}`);
        if (name) params.push(`name=${encodeURIComponent(name)}`);
        if (email) params.push(`email=${encodeURIComponent(email)}`);
        if (status) params.push(`status=${status}`);
        params.push('page=0');
        params.push('size=5');

        url += params.join('&');

        try {
            const response = await fetch(url);
            const users = await response.json();

            let html = '<h3>🔍 分页查询结果（每页5条）：</h3>';
            if (users.length === 0) {
                html += '<p>没有找到匹配的用户</p>';
            } else {
                users.forEach(user => {
                    html += `<div class="user-card">
                            <p><strong>👤 ${user.loginname}</strong> (${user.name})</p>
                            <p><strong>邮箱：</strong> ${user.email || '无'}</p>
                            <p><strong>手机：</strong> ${user.mobilephone || '无'}</p>
                            <p><strong>状态：</strong> <span style="color: ${user.status === 0 ? 'green' : 'red'}">${user.status === 0 ? '✅ 正常' : '❌ 禁用'}</span></p>
                            <p><strong>角色：</strong> `;

                    if (user.roles && user.roles.length > 0) {
                        user.roles.forEach(role => {
                            html += `<span class="role-badge">${role.name}</span>`;
                        });
                    } else {
                        html += '无角色';
                    }
                    html += `</p></div>`;
                });
            }

            document.getElementById('searchResult').innerHTML = html;
        } catch (error) {
            document.getElementById('searchResult').innerHTML = `<p style="color: red;">搜索错误：${error.message}</p>`;
        }
    }
</script>
</body>
</html>